package org.liaohailong.library.http.upload;

import androidx.annotation.NonNull;

import org.liaohailong.library.http.HttpHelper;
import org.liaohailong.library.http.IHttpCallback;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;

/**
 * create by liaohailong
 * time 2022/8/22 14:20
 * desc: 文件上传 进度监听
 */
public class ProgressRequestBody extends RequestBody {
    @NonNull
    private final RequestBody body;
    @NonNull
    private final IHttpCallback<?> callback;

    private BufferedSink bufferedSink;

    public ProgressRequestBody(@NonNull RequestBody body, @NonNull IHttpCallback<?> callback) {
        this.body = body;
        this.callback = callback;
    }

    @Override
    public MediaType contentType() {
        return body.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        return body.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            bufferedSink = Okio.buffer(new ForwardingSink(sink) {
                private long totalCount;
                private long currentCount;

                @Override
                public void write(Buffer source, long byteCount) throws IOException {
                    super.write(source, byteCount);

                    if (totalCount <= 0) {
                        totalCount = ProgressRequestBody.this.contentLength();
                    }

                    currentCount += byteCount;

                    HttpHelper.post2main(() -> {
                        // 主线程回调进度
                        callback.onProgress(currentCount, totalCount);
                    });
                }
            });
        }

        body.writeTo(bufferedSink);
        bufferedSink.flush();
    }
}
